try {
    require("electron-reloader")(module, {});
} catch (_) {
}

// nodejs页面
const {
    app,
    BrowserWindow,
    Menu,
    ipcMain,
    globalShortcut,
    session,
} = require("electron");
const screen = require("electron").screen;
const clipboard = require("electron").clipboard;
const path = require("path");
const store = require("./utils/store");
const excelCmd = require("./utils/excel-cmd");
const {uIOhook, UiohookKey} = require("uiohook-napi");

let mainWindow = null;
let clipboardWindow = null;

/**
 * 主进程接收指令
 */
let mainCmd = {
    isTop: 0,
    timer: null,
    getSize: function (args) {
        return mainWindow.getContentSize();
    },
    paste: function (args) {
        clipboard.writeText(args.text);
    },
    newClipboardWin: function (mouseX, mouseY, width, height, isLeft) {
        clipboardWindow = new BrowserWindow({
            width: width,
            // backgroundColor: '#2e2c29',
            height: height,
            x: mouseX,
            y: mouseY,
            focusable: false,
            transparent: true,
            frame: false,
            resizable: false,
            maximizable: false,
            webPreferences: {
                devTools: true,
                webSecurity: false,
                contextIsolation: true,
                nodeIntegration: true,
                nodeIntegrationboolean: true,
                preload: path.join(__dirname, "preloadClipboard.js"),
            },
        });

        clipboardWindow.loadFile("view\\clipboard-menu\\clipboard.html", {
            query: {
                isLeft: isLeft,
            },
        });
        clipboardWindow.setAlwaysOnTop(true);

        //clipboardWindow.setIgnoreMouseEvents(true);
        clipboardWindow.once("ready-to-show", () => {
            console.log("show");
            clipboardWindow.show();
        });
        //clipboardWindow.webContents.openDevTools();
    },
    /**
     * 失去焦点 隐藏窗口
     * @param args
     */
    closeClipboardWin: function (args) {
        if (clipboardWindow) {
            clipboardWindow.hide();
        }
    },
    appTop: function (args) {
        this.isTop = args["isTop"] == 0 ? 1 : 0;
        if (this.isTop) {
            mainWindow.setAlwaysOnTop(true);
            return this.isTop;
        } else {
            mainWindow.setAlwaysOnTop(false);
            return this.isTop;
        }
    },
    setSize: function (args) {
        clipboardWindow.setSize(args["width"], args["height"]);
    },
    getIsAppTop: function (args) {
        return this.isTop;
    },
    showConsole: function (args) {
        mainWindow.webContents.openDevTools();
    },
    open: function (args) {
        mainWindow
            .loadURL(args["url"])
            .then(() => {
            })
            .catch((res) => {
                if (res.errno != -3) {
                    setTimeout(() => {
                        mainWindow
                            .loadFile("./index.html", {
                                query: {
                                    state: "openFail",
                                },
                            })
                            .catch((res) => {
                                console.log(res);
                            });
                    }, 1000);
                }
                console.log(res);
            });
    },
    loadFile: function (args) {
        mainWindow.loadFile(args["url"]);
    },
};

function showClip(isLeft, clipboardWindowWidth, clipboardWindowHeight, point) {
    clipboardWindow.setBounds({
        x: point.x,
        y: point.y,
        width: clipboardWindowWidth,
        height: clipboardWindowHeight,
    });
    clipboardWindow.flashFrame(false);
    clipboardWindow.showInactive();

    clipboardWindow.webContents.send("menu", {
        cmd: "show",
        isLeft: isLeft,
    });
}

/**
 * 初始化剪切板
 */
function initClipboard() {
    let point = screen.getCursorScreenPoint();
    const primaryDisplay = screen.getPrimaryDisplay();
    const {width, height} = primaryDisplay.workAreaSize;
    let isLeft = 1;
    if (point.x + 800 > width) {
        point.x = point.x - 800;
        isLeft = 0;
    }
    if (point.y + 400 > height) {
        point.y = point.y - 400;
    }
    let clipboardWindowWidth = 800;
    let clipboardWindowHeight = 400;
    if (clipboardWindow) {
        showClip(isLeft, clipboardWindowWidth, clipboardWindowHeight, point);
    } else {
        mainCmd.newClipboardWin(
            point.x,
            point.y,
            clipboardWindowWidth,
            clipboardWindowHeight,
            isLeft
        );
        setTimeout(() => {
            showClip(
                isLeft,
                clipboardWindowWidth,
                clipboardWindowHeight,
                point
            );
        }, 500);
    }
}

/**
 * 注册快捷键point
 */
function registerShortcutKeys() {
    //注册翻译
    globalShortcut.register("Ctrl+alt+f", () => {
        mainWindow.show();
        mainWindow.webContents.send("main", {
            cmd: "translation",
            text: clipboard.readText(),
        });
    });
    //注册剪切板
    globalShortcut.register("Ctrl+Shift+x", () => {
        initClipboard();
    });
    globalShortcut.register("alt+c", () => {
        initClipboard();
    });
}

/**
 * 鼠標監聽
 */
function mousedownListener() {
    uIOhook.on("mousedown", (e) => {
        if (clipboardWindow && clipboardWindow.isVisible()) {
            clipboardWindow.webContents.send("menu", {
                cmd: "mousedown",
                count: 1,
            });
        }
    });
    uIOhook.start();
}

app.commandLine.appendSwitch("js-flags", "--expose-gc");
app.disableHardwareAcceleration();
app.whenReady().then(() => {
    createWindow();
    registerShortcutKeys();
    mousedownListener();
    //mainWindow.close()
    //createWindow("hidden")

    app.on("activate", function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });

    const filter = {
        urls: ["*://*/*"],
    };
    session.defaultSession.webRequest.onBeforeSendHeaders(
        filter,
        (details, callback) => {
            details.requestHeaders["user-agent"] =
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36";
            details.requestHeaders["User-Agent"] =
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36";

            callback({requestHeaders: details.requestHeaders});
        }
    );
});

//注册消息监听
ipcMain.handle("asynchronous-message", handleMsg);

//接收消息
function handleMsg(event, arg) {
    let type = arg["type"];
    arg["window"] = mainWindow;
    let cmd = arg["cmd"];
    if (type == "store") {
        if (cmd == "sqlliteExecute") {
            store.cmd[cmd](arg);
        } else {
            return store.cmd[cmd](arg);
        }
    }
    if (type == "excel") {
        return excelCmd.cmd[cmd](arg);
    }
    if (type == "main") {
        return mainCmd[cmd](arg);
    }
}

function createWindow(titleBarStyle = "default") {
    mainWindow = new BrowserWindow({
        width: 650,
        height: 500,
        webPreferences: {
            nodeIntegration: true,
            webSecurity: false,
            contextIsolation: true,
            nodeIntegrationboolean: true,
            enableRemoteModule: true,
            preload: path.join(__dirname, "preload.js"),
        },
        titleBarStyle: titleBarStyle,
    });

    const Menus = [
        {
            label: "Files",
            submenu: [
                {
                    label: "控制台",
                    role: "console",
                    submenu: [
                        {
                            label: "控制台",
                            click: function () {
                                mainWindow.webContents.openDevTools();
                                //mainWindow.isAlwaysOnTop()
                            },
                        },
                    ],
                },
                {
                    label: "帮助",
                    role: "help",
                    submenu: [
                        {
                            label: "帮助文档",
                            click: function () {
                                dialog.showMessageBoxSync(
                                    {
                                        type: "info",
                                        title: "提示信息",
                                        message: "内容",
                                        buttons: ["ok", "no"],
                                    },
                                    function (index) {
                                        console.log(index);
                                    }
                                );
                            },
                        },
                    ],
                },
            ],
        },
    ];

    mainWindow.setAlwaysOnTop(false);
    const mainMenu = Menu.buildFromTemplate(Menus);
    Menu.setApplicationMenu(null);
    mainWindow.once("ready-to-show", () => {
        mainWindow.show();
    });
    mainWindow.focus(); // 在这里
    mainWindow.loadFile("index.html");

    mainWindow.on("close", () => {
        app.exit();
    });
}

app.on("window-all-closed", function () {
    globalShortcut.unregisterAll();
    if (process.platform !== "darwin") app.quit();
});
